<template>
  <div ref="dend" class="comp"></div>
</template>

<script setup>
import { inject, ref, onMounted, onBeforeUnmount, watch } from "vue";
import { useStore } from "vuex";
let store = useStore();
const echarts = inject("echarts");
const api = inject("api");
// console.log(echarts);
// console.log(api);

// 初始化图标容器ref的值
let dend = ref(null);

// 初始化echarts实例对象
let echartsInstance = null;
// 初始化数据业务
let allData = [];
watch(
  () => store.state.themeName,
  () => {
    echartsInstance.dispose();
    initEcharts();
    enitEcharts();
    asisEcharts();
  }
);
function initEcharts() {
  echartsInstance = echarts.init(dend.value, store.state.themeName);
  let initOptions = {
    title: {
      text: "全国各地种植收成情况",
      top: "3%",
      left: "3%",
    },
    grid: {
      show: false,
      top: "12%",
      left: "3%",
      right: "3%",
      bottom: "3%",
      containLabel: true,
    },
    tooltip: {},
    xAxis: {
      type: "category",
    },
    yAxis: {
      type: "value",
    },
    series: [
      {
        type: "bar",
        label: {
          show: true,
          rotate: "-30",
        },
        itemStyle: {
          // borderRadius: [0, 30, 30, 0],
          color: {
            type: "linear",
            x: 0,
            y: 0,
            x2: 1,
            y2: 0,
            colorStops: [
              {
                offset: 0,
                color: "#FF4B00", // 0% 处的颜色
              },
              {
                offset: 1,
                color: "#FFA100", // 100% 处的颜色
              },
            ],
            // global: false, // 缺省为 false
          },
        },
      },
    ],
  };

  echartsInstance.setOption(initOptions);
}
async function getData() {
  let { data } = await api("plantingHarvest");
  console.log(data);

  allData = data;
  enitEcharts();
}
function enitEcharts() {
  let enitOptions = {
    xAxis: {
      data: allData.map((item) => item.month),
    },
    series: [
      {
        data: allData.map((item) => item.harvest),
      },
    ],
  };
  echartsInstance.setOption(enitOptions);
}
// 手动适配样式
function asisEcharts() {
  let width = dend.value.offsetWidth;
  let scale = (width / 100) * 3.6;
  let initOptions = {
    title: {
      textStyle: {
        fontSize: scale,
      },
    },
    series: [
      {
        barWidth: scale,
        itemStyle: {
          borderRadius: [scale / 2, scale / 2, 0, 0],
        },
      },
    ],
  };
  echartsInstance.setOption(initOptions);
  echartsInstance.resize();
}
onMounted(() => {
  initEcharts(),
    getData(),
    window.addEventListener("resize", asisEcharts),
    asisEcharts();
});
onBeforeUnmount(() => {
  window.removeEventListener("resize", asisEcharts);
});
defineExpose({
  asisEcharts,
});
</script>

<style scoped></style>
